﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Billing.Windows
{
    /// <summary>
    /// Interaction logic for Help.xaml
    /// </summary>
    public partial class Help : Window
    {
        public string code = string.Empty;
        public string desc = string.Empty;

        public Help()
        {
            InitializeComponent();
            txtItemDescription.Focus();
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }

        private void txtItemDescription_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                dGSearchedItems.ItemsSource = null;
                List<Dtos.BillingGridItemDto> items = SearchResult();
                dGSearchedItems.ItemsSource = items;
                if (!(items.Count > 0))
                    dGSearchedItems.ItemsSource = null;

                //dGSearchedItems.Focus();
                dGSearchedItems.SelectedIndex = 0;
            }
            catch (Exception)
            { }
        }

        List<Dtos.BillingGridItemDto> SearchResult()
        {
            try
            {
                List<Dtos.BillingGridItemDto> items = Utilities.CacheManager.BillingItems;
                List<Dtos.BillingGridItemDto> results = new List<Dtos.BillingGridItemDto>();
                string pattern = txtItemDescription.Text.Trim();

                foreach (Dtos.BillingGridItemDto item in items)
                    if (System.Text.RegularExpressions.Regex.IsMatch(item.Name.Trim(), pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        results.Add(item);

                return results;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void txtItemDescription_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && dGSearchedItems.Items.Count > 0)
            {
                code = ((Dtos.BillingGridItemDto)dGSearchedItems.Items[0]).Code.ToString();
                desc = ((Dtos.BillingGridItemDto)dGSearchedItems.Items[0]).Name.ToString();
                this.Close();
            }
        }
    }
}
